<template>
  <div class="Mycontainer" v-loading="getFriendsStore.p">
    <div class="closeButton">
      <i class="el-icon-circle-close" @click="hiddenChat"></i>
    </div>
    <div class="Myblogbody">
      <!-- <div class="menum">
        <div>
          <i class="el-icon-chat-dot-round"></i>
        </div>
        <div>
          <i class="el-icon-menu"></i>
        </div>
        <div>
          <i class="el-icon-user"></i>
        </div>
      </div> -->
      <!-- /用户列表 -->
      <div class="left">
        <div>
          <el-input
            size="mini"
            placeholder="查找联系人或群"
            suffix-icon="el-icon-search"
            v-model="searchText">
          </el-input>
        </div>
        <div
          v-for="(item, index) in friendsList"
          :key="index"
          :class="selectedIndex == index ? 'active' : ''"
          @click="ChangeChat(index, item.messageList, item.user_id)"
        >
          <el-avatar fit="contain" :src="item.user_header" ></el-avatar>
          <span class="hiddenName">{{ item.user_name }} </span>
        </div>
      </div>
      <!-- 用户消息 -->
      <div class="center">
        <!-- 您还未选中或发起聊天，快去跟好友聊一聊吧 -->
        <div class="noFriend" v-if="friendsList.length==0" >
          您暂时没有好友...
        </div>
        <div
          v-show="selectedIndex == index"
          v-for="(item, index) in friendsList"
          :key="index"
          class="panlediv"
        >
          <div class="c_name">@{{ item.user_name }}</div>
          <div class="c_content" id="mycontent" ref="mycontent">
            <div v-if="item.messageList.length != 0">
              <div v-for="(el, inde) in item.messageList" :key="inde">
                <!-- 这里遍历了用户的消息，只能挂在了第一个 -->
                <!-- 不是用户自己的消息 -->
                <div
                  class="content_column_left"
                  v-if="el.from_user_id != $store.state.userInfo.userid"
                >
                  <div>
                    <el-avatar :src="el.user_header"></el-avatar>
                  </div>
                  <div v-if="el.message_type == 1" class="text">
                    {{ el.message }}
                  </div>
                  <div v-if="el.message_type == 2" class="messageIMG">
                    <img :src="el.message" alt="" />
                  </div>
                  <div
                    v-if="el.message_type == 3 && selectedIndex == index"
                    class="chatLocation"
                  >
                    <img
                      :src="url + '?latlng=' + el.message"
                      alt="图片加载失败"
                    />
                  </div>
                </div>
                <!-- 用户自己的消息 -->
                <div v-if="el.from_user_id == $store.state.userInfo.userid">
                  <div class="content_column_right">
                    <div>
                      <el-avatar :src="el.user_header"></el-avatar>
                    </div>
                    <div v-if="el.message_type == 1" class="text">
                      {{ el.message }}
                    </div>
                    <div v-if="el.message_type == 2" class="messageIMG">
                      <img :src="el.message" alt="图片加载失败..." />
                    </div>
                    <div
                      v-if="el.message_type == 3 && selectedIndex == index"
                      class="chatLocation"
                    >
                      <img
                        :src="url + '?latlng=' + el.message"
                        alt="图片加载失败"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="item.messageList.length == 0" class="noMessage">
              <div>暂无消息</div>
            </div>
          </div>
        </div>
        <div class="c_fotter ">
          <div style="width: 95%" class="ml-3">
            <el-dialog
              :visible.sync="mypopp"
              width="45%"
              append-to-body
              custom-class="dialogStyle"
            >
              <localSearch
                ref="qqmap"
                @on-select="addressSelectHandler"
                :type="'1'"
              ></localSearch>
            </el-dialog>
            <el-button
              @click="locationButton"
              slot="reference"
              icon="el-icon-location"
              circle
            ></el-button>
            <el-button icon="el-icon-attract" circle></el-button>
            <el-upload
              :show-file-list="false"
              class="upload-demo"
              action="http://localhost:3001/uploadImg"
              :headers="headers"
              :data="uploadImgMessage"
              multiple
              name="avatar"
              :on-success="uploadSucces"
              :file-list="fileList"
            >
              <el-button icon="el-icon-picture-outline" circle></el-button>
            </el-upload>
          </div>
          <div class="ml-3 mt-1 ">
            <textarea
              v-model="textarea"
              placeholder="输入聊天内容..."
              class="form-control border-0 p-0 shadow-none"
              rows="3"
            ></textarea>
          </div>
          <div style="text-align: right ">
            <el-button class="mr-3" type="primary" round size="mini"
              @click="sentMessage(1, textarea)"
              :disabled="toUserId===''">发送</el-button >
          </div>
        </div>
      </div>
      <div class="right"></div>
    </div>
  </div>
</template>

<script>
import io from "socket.io-client";
import localSearch from "@/components/common/localcationSerch.vue";

export default {
  components: { localSearch },
  data() {
    return {
      socket: window.localStorage.getItem("userinfo")
        ? io("http://localhost:3002", {
          extraHeaders: {
            Authorization: `Bearer ${window.localStorage.getItem("token")}`,
          },
          query: {
            connectUserId: JSON.parse(window.localStorage.getItem("userinfo"))
              .userid,
          },
        })
        : "",
      url: "http://localhost:3001/Tool/getLocationImg",
      headers: {
        Authorization: `Bearer ${window.localStorage.getItem("token")}`,
      },
      uploadImgMessage: {
        test: "",
      },
      fileList: [],
      toUserName: "",
      selectedIndex: 0,
      textarea: "",
      friendsList: [],
      getFriendsStore: this.newStore(),
      getTalkListStore: this.newStore(),
      talkList: [],
      toUserId: "",
      toMessageList: [],
      mypopp: false,
      searchText: '',
    };
  },

  created() {
    if (window.localStorage.getItem("userinfo")) {
      this.getFriendsList();
    }
  },
  mounted() {
    // this.toUserId = this.friendsList[0].userId;
    if (this.socket) {
      this.socket.on("show Message", (data) => {
        for (let i = 0; i < this.friendsList.length; i += 1) {
          if (this.friendsList[i].user_id === data.from_user_id) {
            this.friendsList[i].messageList.push(data);
          }
        }
        setTimeout(() => {
          this.$refs.mycontent.forEach((el) => {
            el.scrollTop = el.scrollHeight;
          });
        }, 100);
      });
      this.socket.on("show Error", () => {
        alert("数据库出错");
      });
    }
  },
  methods: {
    // 选择地址
    addressSelectHandler(row) {
      const latLng = `${row.location.lat},${row.location.lng}`;
      this.sentMessage(3, latLng);
      this.mypopp = false;
    },
    // 显示地图按钮
    locationButton() {
      this.mypopp = !this.mypopp;
    },
    uploadSucces(response) {
      this.imgUrl = response.filePath;
      this.sentMessage(2, this.imgUrl);
    },
    ChangeChat(index, messageList, userId) {
      this.selectedIndex = index;
      this.toUserId = userId;
      this.toMessageList = messageList;
    },
    hiddenChat() {
      this.$emit("hiddenChat");
    },
    getFriendsList() {
      this.spost(this.getFriendsStore, "/getFriendsList", {
        userId: this.$store.state.userInfo.userid,
      }).then((res) => {
        if (res.d.message === '您暂时没有好友！') {
          this.$message.warning('您暂时没有好友');
        } else {
          this.friendsList = res.d.dataList || [];
          this.selectedIndex = 0;
          this.toUserId = this.friendsList[0].user_id || '';
          this.toMessageList = this.friendsList[0].messageList || '';
          setTimeout(() => {
            this.$refs.mycontent.forEach((el) => {
              el.scrollTop = el.scrollHeight;
            });
          }, 0);
        }
      });
    },
    sentMessage(type, mes) {
      const data = {
        message: mes,
        from_user_id: this.$store.state.userInfo.userid,
        to_user_id: this.toUserId,
        user_header: this.$store.state.userInfo.userHeader,
        message_time: new Date(),
        message_type: type,
      };
      this.toMessageList.push(data);
      this.socket.emit("send Message", data);
      // this.talkList.push(data);
      this.textarea = "";
      setTimeout(() => {
        this.$refs.mycontent.forEach((el) => {
          el.scrollTop = el.scrollHeight;
        });
      }, 0);
    },
  },
};
</script>
<style scoped lang="scss">
.Mycontainer {
  /deep/ button {
    outline: none;
  }
  /deep/ .upload-demo {
    display: inline-block;
    margin-left: 10px;
  }
  resize: both;
  position: fixed;
  left: 20%;
  width: 60%;
  top: 10%;
  background: white;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px,
    rgba(0, 0, 0, 0.22) 0px 10px 10px;
  height: 75%;
  z-index: 1998;
  border-radius: 10px;
  overflow: hidden;
  .closeButton {
    height: 5%;
    width: 100%;
    text-align: right;
    font-size: 25px;
    margin-right: 15px;
    i {
      margin-right: 1%;
    }
    i:active {
      color: red;
    }
     i:hover {
      color: red;
    }
  }
  .Myblogbody {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 100%;
    height: 95%;
    .menum {
      min-width: 40px;
      font-size: 30px;
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 5%;
      height: 100%;
      background: #edf2f6;
      color: rgb(66, 66, 66);
      // border-radius: 0 20px 20px 0;
    }
      @media screen and (max-width: 480px) {
        .left{
          width: 15%;
          min-width: auto;
        }
      }
    .left {
      background: white;
      width: 30%;
      min-width: 150px;
      height: 100%;
      .active {
        background: #2bace2;
      }
    }
    .left > div {
      padding: 3% 5%;
      display: flex;
      align-items: center;
      span {
        margin-left: 5%;
      }
    }
    .left > div:hover {
      background: #f4f4f4;
      cursor: pointer;
    }
    .center {
      width: 80%;
      height: 100%;
      background: white;
      overflow: hidden;
      box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;
      .noFriend{
        height: 70%;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
      }
      .panlediv {
        min-width: 150px;
        height: 70%;
        .c_name {
          height: 10%;
          font-size: 20px;
        }
        .messageIMG {
          width: 40%;
          padding: 10px;
          img {
            width: 100%;
            box-shadow: rgba(0, 0, 0, 0.04) 0px 3px 5px;
          }
        }
        .noMessage {
          margin-top: 40%;
          text-align: center;
          color: darkgrey;
        }
        .c_content {
          overflow: auto;
          height: 90%;
          border: #f4f4f4 solid 1px;
          .content_column_left {
            padding: 15px;
            display: flex;
            align-items: flex-start;
            flex-wrap: nowrap;
            flex-shrink: 1;
            .text {
              padding: 5px;
              background: #edf2f6;
              border-radius: 0px 10px 10px 0px;

              margin: 0 10px;
            }
            .chatLocation {
              max-width: 80%;
              height: auto;
              box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px,
                rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
              img {
                max-height: 200px;
              }
            }
          }
          .content_column_right {
            flex-direction: row-reverse;
            padding: 15px;
            display: flex;
            align-items: flex-start;
            flex-wrap: nowrap;
            flex-shrink: 1;
            .text {
              max-width: 80%;
              margin: 0 10px;
              padding: 5px;
              background: #42aaff;
              border-radius: 100px 100px 10px 100px;
            }
            .chatLocation {
              height: auto;
              max-width: 80%;
              box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px,
                rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
              img {
                max-height: 200px;
              }
            }
          }
        }
      }
      .c_fotter {
        width: 100%;
        height: 90%;
      }
    }

    .right {
      display: none;
      // width: 20%;
      // height: 100%;
      // border-left: #f4f4f4 solid 1px;
    }
  }
}
@media screen and (max-width: 375px) {
  .Mycontainer {
    width: 95%;
    left: 2.5%;
    border-radius: 0px;
    .Myblogbody {
      .center {
        width: 100%;
      }
      .right {
        display: none;
      }
    }
  }
  /deep/ .dialogStyle {
    margin-top: 5vh !important;
    width: 100% !important;
  }
}
</style>
